/// Author: QP
/// Version: 1.1
/// Date:2023/05/05
/// HCC 标准设置和设置工具类
Class HCC.Setting Extends %RegisteredObject
{

/// ^HCC用于设置HCC系统级参数
/// ^HCC("HostFacility")=$lb("H123456","系联总医院") - 默认的医院机构号和名称，应使用项目医院的真实数据
/// ^HCC("XSLFilePath")=$system.Util.InstallDirectory()_"csp\xslt" 文档SQL模型转互联互通文档，及互联互通文档转SDA3的XSLT文件路径，默认在安装目录的csp\xslt下
/// ^HCC("DocGenTask")=0 关闭后台产生SQL互联互通文档的任务
/// ^HCC("Debug")=1 Debug模式，该模式会输出SQL XML文档
/// ^HCC("Debug","SQLDocOutputFolder") Debug模式下，输出SQL XML文档的目录
/// ^WS.Setting.Validation设置WS标准的bit串
/// 其第一位为0，表示跳过值集检查。值集检查由WS.DT.CodedString执行；
/// 其第二位为0，表示跳过数据元必要性约束检查。
/// 其第三位为0，表示跳过章节必要性检查。
/// mode = 0:只init hcc 相关，去掉fhir相关初始化 mode = 1:init 所有部分
ClassMethod Init(mode As %Integer = 0, data As %Integer = 0, GKTransFile As %String = "", GKCubecls As %String = "")
{
    Set ^HCC("HostFacility")=$lb("H123456","系联总医院")
    set installPath= ##class(%SYSTEM.Util).InstallDirectory()
    set wPath= installPath_"csp\xslt\HCC\xsl"
    set uPath= installPath_"csp/xslt/HCC/xsl"
    //2 for Windows, 3 for UNIX®, and 0 if not known.
    set os=$ZVERSION(1)
    Set ^HCC("XSLFilePath")= $CASE(os,2: wPath,3: uPath,0: "")
    Set ^HCC("Debug")=1
    Set ^HCC("Debug","SQLDocOutputFolder") = $system.Util.InstallDirectory()_"HCC\samples\"
    Set $bit(^WS.Setting.Validation,1)=0
    Set $bit(^WS.Setting.Validation,2)=0
    Set $bit(^WS.Setting.Validation,3)=0
    set mgrdir=$SYSTEM.Util.ManagerDirectory()
    /// buid data quality cube
    set tsc = ##class(%DeepSee.Utils).%BuildCube("DataQuality")  
    if mode'=0 {
    // 创建FHIR服务器&资源仓库
    write !,"开始创建FHIR服务器&资源仓库..."
     do ..InitFHIRServerEndpoint()
    // 启动sql builder的csp application
    write !,"开始启动sql builder的csp application..."
    do ..EnableSqlBuilderApplication()
    // 注册FHIR服务
    write !,"开始注册FHIR服务..."
    Do ##class(%RoutineMgr).GetWebServerPort(.tWebPort)
    /// 初始化 fhir endpoint
    write !,"开始初始化 fhir service..."
    Do ..InitFHIRServiceReg("HCCFHIRServer",,tWebPort,"/csp/healthshare/"_$NAMESPACE_"/fhir/r4")
    if data'=0 {
    set cn=$NAMESPACE
    // 卸除fhir的数据库
    zn "%SYS"
     write !,"卸载FHIR数据库HCCX0001R"
    do ##class(SYS.Database).DismountDatabase(mgrdir_"HCCX0001R/")
     write !,"卸载FHIR数据库HCCX0001V"
    do ##class(SYS.Database).DismountDatabase(mgrdir_"HCCX0001V/")
    // 替换fhir 数据库
    write !,"替换FHIR数据库HCCX0001R"
    set astatus = $ZF(-100,"/SHELL","mv","-f",mgrdir_"FHIRDEMO/HCCX0001R/IRIS.DAT",mgrdir_"HCCX0001R/IRIS.DAT")
    write !,"替换FHIR数据库HCCX0001V"
    set tstatus = $ZF(-100,"/SHELL","mv","-f",mgrdir_"FHIRDEMO/HCCX0001V/IRIS.DAT",mgrdir_"HCCX0001V/IRIS.DAT")
    // 挂载fhir数据库
    write !,"装载FHIR数据库HCCX0001R"
    do ##class(SYS.Database).MountDatabase(mgrdir_"HCCX0001R/")
    write !,"装载FHIR数据库HCCX0001V"
    do ##class(SYS.Database).MountDatabase(mgrdir_"HCCX0001V/")
    zn cn
    // 添加演示系统的 credential
    do ..InitWSCredential()
    // 初始化FHIR buidler 测试credetial
    write !,"初始化FHIR buidler 测试credetial"
    do ..InitFHIRSQLCredential()
    // 初始化FHIR sql builder 用的fhirrepo
    write !,"初始化FHIR sql builder 用的fhirrepo"
    do ..InitFHIRSQLConfigRepo()
    // 创建执行 analysis
    write !,"创建执行 analysis"
    do ..InitFHIRSQLAnalysis()
    HANG 15
    // 导入 transformation
    write !,"导入 transformation"
    do ..InitFHIRSQLTransformation(GKTransFile)
    // 建立projection
    write !,"建立projection"
    do ..InitFHIRSQLProjection()
    // 导入cube
    do $SYSTEM.OBJ.Load(GKCubecls,"cuk")
    // buid cube 
    do ##class(%DeepSee.Utils).%BuildCube("Guokao.AppointmentCube")
    do ##class(%DeepSee.Utils).%BuildCube("Guokao.ClaimCube")
    do ##class(%DeepSee.Utils).%BuildCube("Guokao.EncounterCube")
    do ##class(%DeepSee.Utils).%BuildCube("Guokao.ConditionCube")
    do ##class(%DeepSee.Utils).%BuildCube("Guokao.ProcedureCube")
    
    }
    
    }
}

/// 初始化FHIR sql builder 用的fhirrepo
ClassMethod InitFHIRSQLConfigRepo()
{
    Set pRepo = {
    "name": "localFHIR",
    "hostname": "localhost",
    "port": "52773",
    "credentialsId": "superuser",
    "repositoryURL": "/csp/healthshare/hcc/fhir/r4",
    "version": 1,
    "sslId": ""
    }
    do ..HttpSender(pRepo,"/csp/fhirsql/api/ui/fhirrepository")
}

/// 初始化FHIR buidler 测试credetial
ClassMethod InitFHIRSQLCredential()
{
   set pCredentials={
    "systemName":"superuser",
    "username":"superuser",
    "password":"fountain"
    }
   do ..HttpSender(pCredentials,"/csp/fhirsql/api/ui/credentials")
}

/// 创建执行 analysis 
ClassMethod InitFHIRSQLAnalysis() As %Status
{
    set pAnalysis={
	"fhirRepositoryId":1,
	"selectivityPercentage":100,
	"startDateTime":""
    }
    do ..HttpSender(pAnalysis,"/csp/fhirsql/api/ui/analysis")
}

/// 导入 transformation 
ClassMethod InitFHIRSQLTransformation(fname As %String = "")
{
    if fname'=""
    {
        #dim pjson as %DynamicObject
      set pjson=##class(%DynamicObject).%FromJSONFile(fname)
      w pjson.%ToJSON()
      do ..HttpSender(pjson,"/csp/fhirsql/api/ui/transformspec")
    }
}

/// 建立projection
ClassMethod InitFHIRSQLProjection()
{
    Set pProjection={
    "fhirRepositoryId": 1,
    "specificationId": 1,
    "packageName": "GuokaoRaw",
    "version": 1
    }
    do ..HttpSender(pProjection,"/csp/fhirsql/api/ui/projection")
}

/// http sender
ClassMethod HttpSender(pJson As %DynamicObject, Url As %String)
{
    kill httprequest
    #dim httprequest as %Net.HttpRequest =##class(%Net.HttpRequest).%New()
    set httprequest.Https=0
    set httprequest.Server="localhost"
    set httprequest.Port=52773
    Do httprequest.SetHeader("Content-Type","application/json")
    do httprequest.SetHeader("Authorization","Basic c3VwZXJ1c2VyOmZvdW50YWlu")
    do httprequest.EntityBody.Write(pJson.%ToJSON())
    //write ##class(HS.Util.StreamUtils).EnsureString(httprequest.EntityBody)
    set tSc = httprequest.Post(Url)
    //write ##class(HS.Util.StreamUtils).EnsureString(httprequest.HttpResponse.Data)
    do httprequest.HttpResponse.OutputToDevice()
}

/// 获得部署医疗机构信息
ClassMethod GetHostFacility() As %String
{
    Return $G(^HCC("HostFacility"))
}

/// 禁用值集检查
ClassMethod DisableVSValid()
{
    Set $bit(^WS.Setting.Validation,1)=0
}

/// 禁用数据元值集约束检查
ClassMethod SkipDEValidation() As %Status
{
    Set $bit(^WS.Setting.Validation,1)=0
    Quit $$$OK
}

/// 启用数据元值集约束检查
ClassMethod EnforceDEValidation() As %Status
{
    Set $bit(^WS.Setting.Validation,1)=1
    Quit $$$OK
}

/// 禁用数据元必要性约束检查
ClassMethod SkipDECardValid() As %Status
{
    Set $bit(^WS.Setting.Validation,2)=0
    Quit $$$OK
}

/// 启用数据元必要性约束检查
ClassMethod EnforceDECardValid() As %Status
{
    Set $bit(^WS.Setting.Validation,2)=1
    Quit $$$OK
}

/// 设置xsl目录
ClassMethod SetXSLPath(pPath) As %Status
{
    Set ^HCC("XSLFilePath")=pPath
    Quit $$$OK
}

/// 启动Debug模式
/// 目前Debug模式下，HCC文档SQL数据源生成文档的过程中，会将文档XML保存到输出文件目录下
ClassMethod EnableDebugMode() As %Status
{
    Set ^HCC("Debug")=1
    Quit $$$OK
}

/// 禁用Debug模式
ClassMethod DisableDebugMode() As %Status
{
    Set ^HCC("Debug")=0
    Quit $$$OK
}

/// 设置Debug模式下输出文档的路径
ClassMethod SetDebugFilePath(pPath) As %Status
{
    Set ^HCC("Debug","SQLDocOutputFolder")=pPath
    Quit $$$OK
}

/// 注册FHIR服务器服务到互联互通套件实例
ClassMethod InitFHIRServiceReg(pServiceName = "HCCFHIRServer", pHost = "127.0.0.1", pPort = "52773", pServiceUrl = "/csp/healthshare/hcc/fhir/r4")
{
    Set tServicename = pServiceName, 
    tHost = pHost, 
    tPort = pPort, 
    tServiceUrl=pServiceUrl
    Do ##class(HS.HC.Util.ServiceRegistrySetup).AddEditHTTPServiceFoundation(tServicename, tHost, tPort, "", tServiceUrl)
}

/// 创建fhir资源仓库 endpoint
ClassMethod InitFHIRServerEndpoint() As %Status
{
 
    Set sc = $$$OK
    set tid = ""
    Set appKey = "/csp/healthshare/"_$REPLACE($ZCONVERT($NAMESPACE,"L"),"$","")_"/fhir/r4"
     &sql( select ID into :tid from HS_FHIRServer.RepoInstance where cspUrl =:appKey)
    if tid '=""
    {
        w "Endpoint 已存在"
        return sc
    }
    Set strategyClass = "HS.FHIRServer.Storage.Json.InteractionsStrategy"
    Set metadataPackages = $lb("hl7.fhir.r4.core@4.0.1","hl7.fhir.us.core@3.1.0")
    //Do ##class(HS.FHIRServer.Installer).InstallNamespace()
    Do ##class(HS.FHIRServer.Installer).InstallInstance(appKey, strategyClass, metadataPackages)
    Set strategy = ##class(HS.FHIRServer.API.InteractionsStrategy).GetStrategyForEndpoint(appKey)
    Set configData = strategy.GetServiceConfigData()
    Set configData.DebugMode = 7
    Set jsonConfigData = configData.AsJSONString()
    do ##class(HS.FHIRServer.Installer).UpdateInstance(appKey,jsonConfigData,1,"","")
    Return sc
}

/// 启动sql buidler 需要的application
ClassMethod EnableSqlBuilderApplication() As %Status
{
    /// /csp/fhirsql  /csp/fhirsql/api/ui /csp/fhirsql/api/repository
    Set sc = $$$OK
    set currentNamespace = $NAMESPACE
    set $ZNSPACE = "%SYS"
    if '((##class(Security.Applications).Exists("/csp/fhirsql"))&&(##class(Security.Applications).Exists("/csp/fhirsql/api/ui"))&&(##class(Security.Applications).Exists("/csp/fhirsql/api/repository")))
    {
        return $$$OK
    }
    do ##class(Security.Applications).Get("/csp/fhirsql",.a)
    set a("Enabled")=1
    do ##class(Security.Applications).Modify("/csp/fhirsql",.a)
    
    do ##class(Security.Applications).Get("/csp/fhirsql/api/ui",.b)
    set b("Enabled")=1
    do ##class(Security.Applications).Modify("/csp/fhirsql/api/ui",.b)

    do ##class(Security.Applications).Get("/csp/fhirsql/api/repository",.c)
    set c("Enabled")=1
    do ##class(Security.Applications).Modify("/csp/fhirsql/api/repository",.c)
    // do something
    set $ZNSPACE = currentNamespace
    write "EnableSqlBuilderApplication success"
    Return sc
}

/// Init Credential for Demo
ClassMethod InitWSCredential() As %Status
{
    
    set sc=##class(Ens.Config.Credentials).SetCredential("EMRAuth","superuser","fountain",1)

    Return sc
}

/// load fhir data from file
ClassMethod FHIRLoader(dir As %String = "") As %Status
{
    Set sc = $$$OK
    if dir =""
    {
    write "从默认位置导入测试数据 <installDir>/lib/fhir"
    set installPath=##class(%SYSTEM.Util).InstallDirectory()
    //2 for Windows, 3 for UNIX®, and 0 if not known.
    set os=$ZVERSION(1)
    Set slash= $CASE(os,2: "\",3: "/",0: "/")
    set dira =installPath_"lib"_slash_"fhir"_slash_"1"_slash
    set dirb =installPath_"lib"_slash_"fhir"_slash_"2"_slash
    set sc = ##class(HS.FHIRServer.Tools.DataLoader).SubmitResourceFiles(dira,"FHIRServer","/csp/healthshare/"_$REPLACE($ZCONVERT($NAMESPACE,"L"),"$","")_"/fhir/r4")
    write sc
    set sc = ##class(HS.FHIRServer.Tools.DataLoader).SubmitResourceFiles(dirb,"FHIRServer","/csp/healthshare/"_$REPLACE($ZCONVERT($NAMESPACE,"L"),"$","")_"/fhir/r4")
    write sc
    }
    set sc = ##class(HS.FHIRServer.Tools.DataLoader).SubmitResourceFiles(dir,"FHIRServer","/csp/healthshare/"_$REPLACE($ZCONVERT($NAMESPACE,"L"),"$","")_"/fhir/r4")
    
    Return sc
}

}
